﻿using System;
using Castle.ActiveRecord;
using NHibernate.Expression;
using Hadlow.Jobvertizer.Models;

namespace Hadlow.Jobvertizer.Repositories
{
    public class Repository<T> : ActiveRecordBase<T>, IRepository<T> where T : Entity
    {
        public T[] GetAll()
        {
            return FindAll();
        }

        public T GetById(int id)
        {
            return FindByPrimaryKey(id);
        }

        public T GetOne(params ICriterion[] criteria)
        {
            return FindOne(criteria);
        }

        public new void Save(T item)
        {
            // we're not following the pattern where the domain object is also the repository
            // because I think that's bad.
            // so use ActiveRecordMediator to save the item, just like the monorail scaffolding
            // framework. (see: Castle.MonoRail.ActiveRecordScaffold.CommonOperationUtils.SaveInstance())

            // tried Save(item), but I got 'NonUniqueObjectException', SaveCopyAndFlush seems to work OK.
            ActiveRecordMediator.SaveCopyAndFlush(item);
        }

        public new void Delete(T item)
        {
            // see Save(T item) above.
            ActiveRecordMediator.Delete(item);
        }

        public new void Refresh(T item)
        {
            ActiveRecordMediator.Refresh(item);
        }
    }
}
